
import { View, Text, Image, Button } from '@tarojs/components'
import styles from "./index.module.scss";
import "./index.scss";
import Taro from "@tarojs/taro";
import { AtFloatLayout } from 'taro-ui'
import { AtButton, AtList, AtListItem, AtProgress, AtCountdown } from 'taro-ui'
import { BaseComponents, Layout, JoinDialog, WinDialog } from "@/components";
import { treasureJoinApi, treasureDetailApi, lotteryUserListApi } from '@/api/detail';
import {timestampToTime} from "@/utils";

import wait from "@/images/treasureDetail/img_seal_wait.png"
import end from "@/images/treasureDetail/img_seal_end.png"
import rule from "@/images/treasureDetail/icon_rule.png"
import rice from "@/images/my/icon_rice.png"
import icon_right from "@/images/common/icon_right.png"
import icon_left from "@/images/common/icon_left.png"
import icon_close from "@/images/common/icon_close.png"
import React, { Fragment } from 'react';



interface Props { }
interface State {
  treasureDetail: any;
  baseInfo: any;
  isOpened: boolean;
  isLottery: boolean;
  winDialog: boolean;
  loadding: boolean;
  loadingButton: boolean;
  animate: boolean;
  index: number;
  lotteryUserList: any[];
  lotteryUserRoll: any[];
}

export default class Index extends BaseComponents<Props, State> {

  constructor(props: Props) {
    super(props);

    this.state = {
      treasureDetail: {},
      baseInfo: {},
      isOpened: false,
      isLottery: false,
      winDialog: false,
      loadding: false,
      loadingButton: false,
      animate: false,
      index: 0,
      lotteryUserList: [],
      lotteryUserRoll: [],
    };
  }

  componentWillMount() { }

  componentDidMount() {
    this.setState({ loadding: true });
    this.gerDetail();
    this.getLotteryUserList();
  }

  componentWillUnmount() { }

  componentDidShow() {

  }

  componentDidHide() { }

  //下拉时触发的函数
  onPullDownRefresh() {
    let pages = Taro.getCurrentPages();;
    let currPage: any = null;
    if (pages.length) {
      currPage = pages[pages.length - 1];
    };
    currPage.onShow();
    Taro.stopPullDownRefresh();
  }

  getLotteryUserList = () => {
    const code = Taro.getCurrentInstance().router.params.code;
    lotteryUserListApi(1, 10, code).then((res: any) => {
      if (res) {
        this.setState({ lotteryUserList: res.records, lotteryUserRoll: res.records.slice(0, 30) });
        if (res.records.length > 1) setInterval(this.Dt, 5000);
      }
    })
  }

  Dt = () => {
    this.setState({ animate: true });
    this.state.lotteryUserRoll.push(this.state.lotteryUserRoll[0]);
    setTimeout(() => {
      this.state.lotteryUserRoll.shift();
      this.setState({ animate: false });
    }, 1000)
  }

  gerDetail = () => {
    const code = Taro.getCurrentInstance().router.params.code;
    const userInfo = Taro.getStorageSync("userInfo");
    treasureDetailApi(code, userInfo.code).then((res: any) => {
      this.setState({ loadding: false });
      res.lottery.percent = Math.floor((res.lottery.currentCredits / res.lottery.totalCredits) * 100);
      // res.userLuckyCodes=["45466465","456464","546463"]
      if (res.userLuckyCodes && res.userLuckyCodes.length > 0) {
        res.userLuckyCode = res.userLuckyCodes.join(",");
      }
      this.setState({ treasureDetail: res, baseInfo: res.lottery });
      if (res.userJoinStatus == 1 && (res.userStatus == 1 || res.userStatus == 2)) {
        this.setState({ isLottery: true })
      }
      if (res.userJoinStatus == 1 && (res.userStatus == 2)) {
        this.setState({ winDialog: true })
      }

    });
  }

  join = () => {
    const lotteryCode = Taro.getCurrentInstance().router.params.code;
    const userInfo = Taro.getStorageSync("userInfo");
    this.setState({ loadingButton: true });
    treasureJoinApi({ lotteryCode, userCode: userInfo.code }).then((res: any) => {
      this.setState({ loadingButton: false });
      if (res) {
        this.setState({ isOpened: true });
        this.gerDetail();
        this.getLotteryUserList();
      }
    });
  }
  goLotteryUserList = () => {
    const lotteryCode = Taro.getCurrentInstance().router.params.code;
    Taro.navigateTo({ url: `/pages/lotteryUserList/index?code=${lotteryCode}` });
  }

  goAdsWebView = (webUrl) => {
    Taro.navigateTo({
      url: `/pages/webView/index?webUrl=${webUrl}`
    })
  }

  handleClose() {
    this.setState({ isLottery: false })
  }


  // userJoinStatus 0未参加 1已参加
  //userStatus  待开奖： 0,未中奖： 1, 中奖: 2
  render() {
    const { treasureDetail, baseInfo, isOpened, isLottery, index, loadding, winDialog, lotteryUserList, lotteryUserRoll, loadingButton, animate } = this.state;
    const getAds = Taro.getStorageSync("getAds") ? Taro.getStorageSync("getAds") : []
    return (
      <Layout navBar title="夺宝详情" visibleIcon loadding={loadding}>
        <View className={styles.index} style={{ "paddingBottom": (baseInfo.percent == 100 || (treasureDetail.userLuckyCodes && baseInfo.joinLimit <= treasureDetail.userLuckyCodes.length)) ? "0px" : "74px" }}>
          <View className={styles.banner}>
            <Image src={baseInfo.bannerImg ? baseInfo.bannerImg : ""} mode="aspectFit"></Image>
            {treasureDetail.userJoinStatus == 1 && treasureDetail.userStatus == 0 && <Image src={wait} className={styles.treasureStatus}></Image>}
            {treasureDetail.userStatus != 0 && <Image src={end} className={styles.treasureStatus}></Image>}

            <View className={styles.rule} onClick={() => { Taro.navigateTo({ url: `/pages/rule/treasureRule/index?baseInfo=${JSON.stringify(baseInfo) }`}) }}>
              <Text>夺宝规则</Text>
              <Image src={rule}></Image>
            </View>
            {lotteryUserRoll.length > 0 && <View className={styles.announce} onClick={() => this.goLotteryUserList()}>
              <View  className={`${styles.announceItems} ${animate && styles.anim}`} >
                {lotteryUserRoll.map((item, index) => {
                  return <View key={index} className={styles.announceItem}>
                    <Image src={item.avatar}></Image>
                    <View>{item.alias}  参与{item.credits}积分</View>
                    <Text>{timestampToTime(item.modifiedOn)}</Text>
                  </View>
                })}
              </View>

            </View>}

          </View>

          <View className={styles.middle}>
            <AtProgress percent={baseInfo.percent} strokeWidth={16} color='#7676FA' isHidePercent className={styles.atProgress} />
            <Text>{baseInfo.percent}%</Text>
          </View>

          <View className={styles.goodsInfo}>
            <Text>{baseInfo.content}</Text>
            <View className={styles.goodsInfo_middle}>
              <Text>单次参与需</Text>
              <Text className={styles.price}>{baseInfo.credits}</Text>
              <Image src={rice}></Image>
              <Text className={styles.price_old}>¥{baseInfo.originalPrice}</Text>
              <View className={styles.number}>数量 x {baseInfo.giftNum}</View>
            </View>
          </View>

          <View className={styles.personNum}>
            {lotteryUserList.length > 0 && <View className={styles.lotteryUser} onClick={() => this.goLotteryUserList()}>
              {lotteryUserList.slice(0, 3).map((item, index) => {
                return <Image src={item.avatar} key={index}></Image>
              })}
            </View>}

            <View>{baseInfo.joinCnt}人已参与｜{baseInfo.totalCredits}米粒即可开奖</View>
          </View>

          {treasureDetail.userLuckyCodes && treasureDetail.userLuckyCodes.length > 0 && <View className={styles.myTreasure}>
            <View>- 我的抽奖码 -</View>
            <Text className={styles.number}>{treasureDetail.userLuckyCode}</Text>
            {treasureDetail.userLuckyCodes && treasureDetail.userLuckyCodes.length > 0 && <Text className={styles.time}>{treasureDetail.userLuckyCodes.length}次</Text>}
          </View>}


          <View className={styles.detail}>
            <Image onClick={() => this.goAdsWebView(getAds[2].ads[0].url)} src={getAds.length > 0 && getAds[2].ads[0].adImg} mode="widthFix"></Image>
            <Image src={baseInfo.contentImg1} mode="widthFix"></Image>
            <Image src={baseInfo.contentImg2} mode="widthFix"></Image>
            <Image src={baseInfo.contentImg3} mode="widthFix"></Image>
          </View>

          {(baseInfo.percent == 100 || (treasureDetail.userLuckyCodes && baseInfo.joinLimit <= treasureDetail.userLuckyCodes.length)) ? null : <View className={styles.bottom}><Button className={styles.batton} onClick={() => { this.join() }} loading={loadingButton} disabled={loadingButton}>{loadingButton ? null : "参与兑换抽奖码"}</Button></View>
          }


        </View>
        <JoinDialog isOpened={isOpened} onCancel={() => { this.setState({ isOpened: false }) }}></JoinDialog>

        <WinDialog isOpened={winDialog} onCancel={() => { this.setState({ winDialog: false }) }}></WinDialog>

        {isLottery && <Image src={icon_close} className={styles.close} onClick={() => this.setState({ isLottery: false })}></Image>}
        <AtFloatLayout isOpened={isLottery} onClose={this.handleClose.bind(this)} >
          <View className={styles.content}>
            {treasureDetail.winUsers && treasureDetail.winUsers.map((item, i) => {
              return (index == i && <Fragment key={i} >
                <Image src={item.avatar}></Image>
                <View className={styles.name}>{item.alias}</View>
                <View className={styles.middle}>
                  <View>- 中奖号 -</View>
                  <View className={styles.lotteryNum}>
                    {item.myLuckyCode.split("").map((num, j) => {
                      return <View key={j} className={styles.lotteryNum_item}>{num}</View>
                    })}
                  </View>
                </View>
              </Fragment>
              )
            })}
            {treasureDetail.winUsers && treasureDetail.winUsers.length > 1 && index != 0 && <Image src={icon_left} className={styles.icon_left} onClick={() => this.setState({ index: index - 1 })}></Image>}
            {treasureDetail.winUsers && treasureDetail.winUsers.length > 1 && index < treasureDetail.winUsers.length - 1 && <Image src={icon_right} className={styles.icon_right} onClick={() => this.setState({ index: index + 1 })}></Image>}


            <button className={styles.line_button} onClick={() => this.setState({ isLottery: false })}>{treasureDetail.userStatus == 2 ? "恭喜你中奖了！" : "未中奖~加油！再接再厉"}</button>
          </View>
        </AtFloatLayout>

      </Layout>
    )
  }
}
